package com.sdtv.basemodule.http.interceptors;

import android.util.Log;

import com.sdtv.basemodule.BuildConfig;
import com.sdtv.basemodule.utils.HttpUtil;

import java.io.IOException;
import java.nio.charset.Charset;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

/**
 * @ProjectName: MediunFusion
 * @Package: com.sdtv.basemodule.http.interceptors
 * @ClassName: ExceptionInterceptor
 * @Description: j异常响应处理 --
 * @Author: 小郭同学
 * @CreateDate: 2019-06-24 15:42
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public abstract class ExceptionInterceptor implements Interceptor {

    private static final String TAG = "ExceptionInterceptor";

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);
        ResponseBody responseBody = response.body();
        BufferedSource source = responseBody.source();
        source.request(Long.MAX_VALUE);
        MediaType contentType = responseBody.contentType();
        Charset charset = HttpUtil.UTF8;
        if (null != contentType) {
            charset = contentType.charset(HttpUtil.UTF8);
        }
        //返回流内容--
        Buffer buffer = source.buffer();
        String bodyString = buffer.clone().readString(charset);
        if (BuildConfig.DEBUG) {
            Log.e(TAG, "网络拦截器:" + bodyString + " host:" + request.url().toString());
        }

        boolean isText = HttpUtil.isText(contentType);
        if (!isText) {
            return response;
        }
        //判断响应是否过期（无效）
        if (isResponseExpired(response, bodyString)) {
            return responseExpired(chain, bodyString);
        }
        return response;
    }


    /**
     * 处理响应是否有效
     * <p>
     * 这里可以处理自己的逻辑 比如token过期 等等
     */
    public abstract boolean isResponseExpired(Response response, String bodyString);

    /**
     * 无效响应处理
     */
    public abstract Response responseExpired(Chain chain, String bodyString);
}
